package com.springboot.search.controller;

import com.springboot.search.common.result.Result;
import com.springboot.search.dao.SearchDao;
import com.springboot.search.entity.ESGoods;
import com.springboot.search.service.ESGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;


@Controller
public class SearchController {

    @Autowired
    SearchDao dao;
    @Autowired
    ESGoodsService esGoodsService;

    @RequestMapping("/index")
    public String index(){
        return "/index.html";
    }
    @RequestMapping("/goodsDetail")
    public String goodsDetail(){
        return "/goodsDetail.html";
    }

    @RequestMapping("/searchGoods.json")
    @ResponseBody
    public Result searchGoods(String search){
        try{
            return Result.success(dao.queryGoods(search));
        }catch (Exception e){
            return Result.fail("查询商品出错！");
        }
    }

    @RequestMapping("/searchGoodsByES.json")
    @ResponseBody
    public Result searchGoodsByES(String search){
        try{
          List<ESGoods> goods=new ArrayList<>();
          if (search!=null&&!search.equals("")){
              goods=esGoodsService.searchEsGoods(search);
          }else {
              goods=esGoodsService.findAll();
          }
          return Result.success(goods);
        }catch (Exception e){
          return Result.fail("未启动elasticsearch服务");
        }
    }

    @RequestMapping("/searchGoodsNameByES.json")
    @ResponseBody
    public Result searchGoodsNameByES(String search){
        try{
            List<String> goods=new ArrayList<>();
            if (search!=null&&!search.equals("")){
                goods=esGoodsService.searchESGoodsList(search);
            }
            return Result.success(goods);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("未启动elasticsearch服务");
        }
    }

    /**
     * 根据id获取单条数据
     * @param id
     * @return
     */
    @GetMapping("/searchGoodsById.json")
    @ResponseBody
    public Result searchGoodsById(Integer id){
        try{
            ESGoods esGoods=esGoodsService.searchESGoodsById(id);
            if (esGoods!=null){
                return Result.success(esGoods);
            }else {
                return Result.fail("未查询到你想要的商品！");
            }
        }catch (Exception e){
            return Result.fail("未启动elasticsearch服务");
        }
    }
}
